package com.github.live.receiver;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.github.live.activity.LivePlayActivity;
import com.github.live.manager.ChannelsManager;
import com.github.live.manager.LiveInitializer;
import com.github.live.util.LogFactory;
import com.github.livebase.bean.Channel;
import com.github.livebase.bean.ChannelGroup;
import com.github.livebase.util.StringKeyValuePairs;
import com.github.livebase.util.base.CollectionsUtil;

import java.util.List;


public class ChannelReceiver extends CloseableReceiver  {
    public static String action = "com.github.live.CHANNEL_OPEN";
    @Override
    public void onReceive(Context context, Intent intent) {
        ChannelsManager cm = null;
        try {
            cm = LiveInitializer.getInitializer().getChannelsManager();
        }
        catch (RuntimeException e) {
            LiveInitializer li = LiveInitializer.getInitializer();
            li.init();
            cm = li.getChannelsManager();
        }

        toTarget(context, intent);

        Intent live = new Intent(context, LivePlayActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        live.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        live.putExtra("number", cm.getCurrentChannel().getNumber());
        LogFactory.debug(ChannelReceiver.class, "open app invoke");
        context.startActivity(live);
    }

    public void toTarget(Context context, Intent intent) {
        if (!action.equals(intent.getAction())) {
            return;
        }

        if (intent.getBooleanExtra("open_only", false)) {
            LogFactory.debug(ChannelReceiver.class, "just open the live app");
            return;
        }

        // 根据频道号跳转
        int number = intent.getIntExtra("number", -1);
        if (number != -1) {
            LiveInitializer.getInitializer()
                    .getChannelsManager()
                    .setActiveByNumber(number);
            LogFactory.debug(ChannelReceiver.class, "change chanel by number[{}]", number);
            return;
        }

        // 根据id跳转
        String id = intent.getStringExtra("id");
        if (!TextUtils.isEmpty(id) && setActiveByFilter((c)-> id.equals(c.getId()) )) {
            LogFactory.debug(ChannelReceiver.class, "change chanel by id[{}]", id);
            return;
        }

        // 根据name跳转
        String name = intent.getStringExtra("name");
        if (!TextUtils.isEmpty(name) && setActiveByFilter((c)-> name.equals(c.getName()) )) {
            LogFactory.debug(ChannelReceiver.class, "change chanel by name[{}]", name);
            return;
        }

        // 根据附加信息进行跳转
        String opt = intent.getStringExtra("opt");
        if (!TextUtils.isEmpty(opt)) {
            StringKeyValuePairs pairs = StringKeyValuePairs.createKeyValuePairs(opt, "=");
            if (!TextUtils.isEmpty(pairs.getKey()) && !TextUtils.isEmpty(pairs.getValue())
                && setActiveByFilter((c) -> pairs.getValue().equals(c.get(pairs.getKey())))) {
                LogFactory.debug(ChannelReceiver.class, "change chanel by opt[{}]", opt);
                return;
            }
        }

        int offset = intent.getIntExtra("offset", 0);
        if (offset != 0) {
            ChannelsManager cm = LiveInitializer.getInitializer().getChannelsManager();
            if (offset > 0) {
                cm.nextChannel();
            } else {
                cm.preChannel();
            }
            LogFactory.debug(ChannelReceiver.class, "change chanel by offset[{}]", offset);
            return;
        }
        LogFactory.debug(ChannelReceiver.class, "received a OPEN_CHANNEL broadcast but nothing to do");
    }

    private boolean setActiveByFilter(CollectionsUtil.Filter<Channel> filter) {
        ChannelsManager cm = LiveInitializer.getInitializer().getChannelsManager();
        List<ChannelGroup> groups = cm.getLiveChannelGroups();
        for (int i = 0, l = groups.size(); i < l; i++) {
            ChannelGroup group = groups.get(i);
            int channelIndex = CollectionsUtil.firstIndex(group.getChannels(), filter);
            if (channelIndex == -1) {
                continue;
            }
            cm.setActiveByGroupIndexAndChannelIndex(i, channelIndex);
            return true;
        }
        return false;
    }
}